<template>
  <div class="login-page">
    <!-- 使用element-ui，组件名就是类名 -->
    <el-card>
      <template #header>黑马面经后台管理系统</template>
      <el-form ref="form" label-width="60px" :model="user" :rules="rules">
        <!-- 账号 -->
        <el-form-item label="账号" prop="username">
          <el-input v-model="user.username"></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item label="密码" prop="password">
          <el-input v-model="user.password" show-password></el-input>
        </el-form-item>
        <!-- 按钮 -->
        <el-form-item>
          <el-button type="primary" @click="login">登录</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { loginAPI } from '@/api/user'

export default {
  name: 'LoginIndex',
  data () {
    return {
      // 提交的数据
      user: {
        username: 'admin',
        password: 'admin'
      },
      // 验证规则
      rules: {
        username: [
          // require表示必填，message表示验证不通过提示信息，trigger触发时机
          { required: true, message: '请输入账号', trigger: 'blur' },
          {
            min: 3,
            max: 8,
            message: '长度在 3 到 8 个字符',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 3,
            max: 8,
            message: '长度在 3 到 8 个字符',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    login () {
      // 首先进行完整性检查
      this.$refs.form.validate(async valid => {
        // console.log(valid) 如果验证通过-true，不通过为false
        if (valid) {
          // 进入这个区间表示通过，此时可以提交数据
          // console.log(this.user)
          try {
            const res = await loginAPI(this.user)
            console.log(res)
            // 登录成功后，将token保存到本地
            // localStorage.setItem('mj-pc-token', res.data.token)
            this.$store.commit('user/updateToken', res.data.token)
            this.$message.success('登录成功')
            // 跳转到首页
            this.$router.push('/dashboard')
          } catch (err) {
            if (err.response) {
              this.$message.error(err.response.data.message)
            } else {
              this.$message.error('登录失败，请稍后再试')
            }
          }
        }
      })
    },
    reset () {
      this.$refs.form.resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.login-page {
  height: 100vh;
  background: url(@/assets/login-bg.svg) no-repeat center / cover;
  .el-card {
    width: 420px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    // 样式穿透，用于修改子组件的样式
    ::v-deep .el-card__header {
      text-align: center;
      background-color: #727cf5;
      color: white;
      height: 80px;
      line-height: 40px;
    }
    .el-form {
      margin: 0 20px;
      .el-button {
        margin: 0 30px;
      }
    }
  }
}
</style>
